{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "44db8a6b",
   "metadata": {},
   "source": [
    "`asyncio` 是Python 3.4及以上版本提供的标准库 ，用于编写异步I/O并发代码，可在单线程中高效处理大量并发I/O操作。以下是其使用方法和示例：\n",
    "\n",
    "### 基本概念\n",
    "- **协程（Coroutine）**：通过 `async def` 定义的函数，是 `asyncio` 实现异步的基础。调用协程函数不会立即执行，而是返回一个协程对象。例如 `async def my_coro(): pass` ，调用 `my_coro()` 得到的是协程对象。\n",
    "- **事件循环（Event Loop）**：`asyncio` 的核心，负责管理和调度协程任务。它不断检查任务状态，决定哪些任务可以执行。\n",
    "- **`await` 关键字**：用于在协程中暂停执行，等待可等待对象（如另一个协程、`asyncio.Future` 等）完成。\n",
    "\n",
    "### 使用步骤\n",
    "1. **定义协程函数**：使用 `async def` 定义，在函数内部通过 `await` 挂起协程执行，实现异步操作。\n",
    "2. **创建事件循环**：早期写法是 `loop = asyncio.get_event_loop()` 来获取事件循环对象。Python 3.7+ 推荐使用 `asyncio.run()` ，它会自动创建、运行并关闭事件循环。\n",
    "3. **将协程注册到事件循环并执行**：可以使用 `loop.run_until_complete(coro())` （旧方式）运行单个协程；用 `asyncio.gather(*coros)` 并发运行多个协程，再用 `asyncio.run()` 执行。\n",
    "\n",
    "### 示例\n",
    "#### 简单异步函数示例\n",
    "```python\n",
    "import asyncio\n",
    "\n",
    "# 定义协程函数\n",
    "async def greet():\n",
    "    print(\"hello, \")\n",
    "    await asyncio.sleep(1)  # 模拟异步操作，暂停1秒\n",
    "    print(\"world!\")\n",
    "\n",
    "# 使用asyncio.run运行协程\n",
    "asyncio.run(greet())\n",
    "```\n",
    "这里定义了 `greet` 协程函数，`await asyncio.sleep(1)` 使函数暂停1秒，期间不阻塞其他操作，最后 `asyncio.run` 执行该协程。\n",
    "\n",
    "#### 并发运行多个协程示例\n",
    "```python\n",
    "import asyncio\n",
    "\n",
    "# 定义第一个异步函数\n",
    "async def say_hello():\n",
    "    print(\"hello!\")\n",
    "    await asyncio.sleep(1)\n",
    "    print(\"done saying hello.\")\n",
    "\n",
    "# 定义第二个异步函数\n",
    "async def say_goodbye():\n",
    "    print(\"goodbye!\")\n",
    "    await asyncio.sleep(2)\n",
    "    print(\"done saying goodbye.\")\n",
    "\n",
    "# 定义主协程函数并发运行多个异步函数\n",
    "async def main():\n",
    "    await asyncio.gather(say_hello(), say_goodbye())\n",
    "\n",
    "asyncio.run(main())\n",
    "```\n",
    "此例中，`say_hello` 和 `say_goodbye` 是两个异步函数，`asyncio.gather` 让它们并发执行，`asyncio.run` 启动主协程 `main` 。\n",
    "\n",
    "#### 使用异步队列示例\n",
    "```python\n",
    "import asyncio\n",
    "\n",
    "# 定义处理队列元素的协程\n",
    "async def worker(queue):\n",
    "    while not queue.empty():\n",
    "        item = await queue.get()  # 从队列获取元素\n",
    "        print(f'processing {item}')\n",
    "        await asyncio.sleep(1)  # 模拟处理时间\n",
    "        queue.task_done()  # 标记任务完成\n",
    "\n",
    "async def main():\n",
    "    queue = asyncio.Queue()\n",
    "    # 往队列添加元素\n",
    "    for i in range(5):\n",
    "        queue.put_nowait(i)\n",
    "    # 创建多个worker协程处理队列元素\n",
    "    tasks = [worker(queue) for _ in range(2)]\n",
    "    await asyncio.gather(*tasks)\n",
    "    await queue.join()  # 等待队列所有任务完成\n",
    "\n",
    "asyncio.run(main())\n",
    "```\n",
    "该示例通过异步队列 `asyncio.Queue` 协调任务，`worker` 协程从队列取元素处理，多个 `worker` 协程并发工作。 \n",
    "\n",
    "\n",
    "\n",
    "### 其他常用方法\n",
    "- **`asyncio.create_task()`**：用于将协程包装成 `Task` 对象并立即加入事件循环调度，可在运行中动态添加任务。如 `task = asyncio.create_task(my_coro())` 。\n",
    "- **`asyncio.wait()`**：和 `asyncio.gather()` 类似，用于等待多个协程完成，但返回值和控制方式略有不同。例如 `await asyncio.wait([coro1(), coro2()])` 。 \n",
    "\n",
    "\n",
    "\n",
    "`asyncio` 适用于网络爬虫、Web 服务高并发处理、文件读写等I/O密集型场景，能显著提升程序并发性能 。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f456227",
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "\n",
    "# 定义协程函数\n",
    "async def greet():\n",
    "    print(\"hello, \")\n",
    "    await asyncio.sleep(1)  # 模拟异步操作，暂停1秒\n",
    "    print(\"world!\")\n",
    "\n",
    "# 使用asyncio.run运行协程\n",
    "# asyncio.run(greet())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "project_practice",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
